//
//  FPToRepayDetailController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/3/13.
//

#import "FPToRepayDetailController.h"
#import "FPLoanDetailHeader.h"
#import "FPToRepayDetailFooterView.h"
#import "FPToRepayDetailCell.h"
#import "FPRepayController.h"
#import "FPLoanDetailModel.h"

@interface FPToRepayDetailController () <UITableViewDelegate , UITableViewDataSource , DZNEmptyDataSetSource , DZNEmptyDataSetDelegate , UIScrollViewDelegate>

@property (nonatomic , strong) FPLoanDetailHeader *headerView;

@property (nonatomic , strong) FPToRepayDetailFooterView *footerView;

@property (nonatomic , strong) FPLoanDetailModel *loanModel;

@end

@implementation FPToRepayDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    [self setTitle:@"本月待还" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - 80.f);
    
    self.tableView.backgroundColor = UIColor.clearColor;
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPLoanDetailHeader.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPToRepayDetailFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - 80.f - UIDevice.safeDistanceBottom, SCREEN_WIDTH, 80.f + UIDevice.safeDistanceBottom);
    
    // iOS 15+ 解决顶部间距问题
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0; // 取消自动顶部间距
    }
    
    self.tableView.rowHeight = 156.f;
    
    [self.footerView.repayBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self repayAction];
    }];
    
    [self getData];
}

- (void)getData {
    
    [MBManager showLoading];
    [FPLoanDetailModel getRepayMentSuccess:^(NSInteger code, NSString * _Nonnull message, FPLoanDetailModel * _Nonnull model) {
        [MBManager hideLoading];
        
        [self.dataSource removeAllObjects];
        
        self.loanModel = model;
        
        self.headerView.amountLab.text = model.repaymentSummary.totalAmountToPay;
        
        if (model.repaymentSummary.totalPenalInterest.floatValue > 0.f) {
            
            self.headerView.retaLab.text = [NSString stringWithFormat:@"本金：%.2f元 ｜ 利息：%.2f元 ｜ 罚息：%.2f元" , model.repaymentSummary.totalPrincipal.floatValue , model.repaymentSummary.totalInterest.floatValue , model.repaymentSummary.totalPenalInterest.floatValue];
        }
        else {
         
            self.headerView.retaLab.text = [NSString stringWithFormat:@"本金：%.2f元 ｜ 利息：%.2f元" , model.repaymentSummary.totalAmountToPay.floatValue , model.repaymentSummary.totalInterest.floatValue];
        }
        
        self.footerView.amountLab.text = [NSString stringWithFormat:@"%.2f元", model.repaymentSummary.totalAmountToPay.floatValue];
         
        for (FPLoanDetailListModel *m in model.repaymentSchedules) {
            
            [self.dataSource addObject:m];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 35.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *lab = [[UILabel alloc] init];
    lab.font = [UIFont systemFontOfSize:16.f weight:(UIFontWeightSemibold)];
    lab.textColor = [UIColor hexColor:@"#3A3A3A"];
    lab.text = @"    还款明细";
    
    if (self.loanModel.repaymentSummary.totalAmountToPay.floatValue <= 1.f) {
        
        lab.text = @"    暂无待还款";
    }
        
    lab.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    return lab;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPToRepayDetailCell *cell;
    
    if (!cell) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPToRepayDetailCell.class) owner:nil options:nil].lastObject;
    }
    
    FPRepaymentSchedules *model = self.dataSource[indexPath.row];
    
    [cell analysisAmount:model.dueAmount];
    
    [cell analysisRepayCurrenLimit:model.installmentNumber totalLimit:model.lengthOfMaturity];
    [cell analysisBorrowTime:model.createTime];
    
    
    // 罚息
    if (model.status.integerValue == 2) {
        
        cell.rateLab.text = [NSString stringWithFormat:@"本金：%.2f元 + 利息：%.2f元 + 罚息：%.2f元" , model.principal.floatValue , model.interest.floatValue , model.penalInterest.floatValue];
        // 逾期UI
        [cell analysisPenal:YES days:model.overdueDay];
    }
    else {
        
        cell.rateLab.text = [NSString stringWithFormat:@"本金：%.2f元 + 利息：%.2f元" , model.principal.floatValue , model.interest.floatValue];
        // 逾期UI 
        [cell analysisPenal:NO days:model.overdueDay];
    }
    
    return cell;
}

#pragma mark - 确认还款
- (void)repayAction {
    
    if (self.loanModel.repaymentSummary.totalAmountToPay.floatValue <= 1.f) {
        
        [self showText:@"当前无需还款"];
        return;
    }
    FPRepayController *vc = [[FPRepayController alloc] init];
    vc.amountString = self.loanModel.repaymentSummary.totalAmountToPay;
//    vc.termString = [NSString stringWithFormat:@"%02zd/%@期",88, @"18"];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
